define(function(require, exports, module) {

	require("validator");
	require("config")
	require("modal");

	var LOGIN_API = "/api/login";
	var INDEX_LOCATION = "index.html";

	$.extend({
		validateResult : function(isValidate, fields, passes, errors) {
			$(fields).removeClass("error");
			var form = $("form");
			form.children("div").remove();
			if(!isValidate) {
				errors[0].field.focus();
				$(errors[0].field).addClass("error");
				$('<div class="error">'+errors[0].error+'</div>').appendTo(form);
			}
		}
	});

	module.exports = {

		start : function() {
			var me = this;
			$("title").text($.i18n.prop("login.title") + "-" + $.i18n.prop("system.title"));
			$("h1").text($.i18n.prop("system.title"));
			$("input[name=username]").attr({
				placeholder:$.i18n.prop("login.username.placeholder"),
				label:$.i18n.prop("login.username")
			});
			$("input[name=password]").attr({
				placeholder:$.i18n.prop("login.password.placeholder"),
				label:$.i18n.prop("login.password")
			});
			$("button[name=submit").on("click", function() {
				me.login();
			});
			document.onkeydown = function () {
		        if (window.event && window.event.keyCode == 13) {
		            window.event.returnValue = false;
		            me.login();
		        }
		    }
		},
		login: function() {
			var form = $("form");
			var data = form.serialize();
			if(form.validate()) {
				$("button").prop("disabled", true);
				$.post(LOGIN_API, data, function(resp) {
					$("button").prop("disabled", false);
					if(resp.success) {
						window.location.href = INDEX_LOCATION;
					} else {
						$('<div class="error">'+$.i18n.prop("login.error.invalid")+'</div>').appendTo($("form"));
					}
				}, "json");
			}
		}

	};

});